<template>
  <div class="m-25 mt-65">
    <div class="normal-box-mod">
      <div class="normal-box-hd clearfix">
        <div class="normal-box-title">
          <div class="decorate-square"></div>
          <h2>数据源管理</h2>
        </div>
      </div>
      <div class="normal-box-bd">
      <div class="normal-list-page-mod">
        <div class="normal-list-page-hd clearfix">
          <Button-group>
            <Button custom-icon="iconfont icon-shanchusekuai" size="small" type="error" @click="batchDel">
              删除
            </Button>
            <Button custom-icon="iconfont icon-fangkuai2" size="small" type="primary" @click="showCreateModal">
              新建
            </Button>
          </Button-group>
          <Input v-model="queryData.name" placeholder="请输入名称" style="width: 200px;margin-left:50px;">名称</Input>
          <DatePicker  :value="queryData.time" type="datetimerange" format="yyyy-MM-dd HH:mm" split-panels placeholder="选择起止日期" style="width: 250px" @on-change="selectTime" @on-clear="clearTime"></DatePicker>
          <Button type="primary" custom-icon="iconfont icon-chaxun" size="small" @click="goSearch">搜索</Button>
        </div>
        <div class="normal-list-page-bd">
          <Table border :loading="list.loading" :columns="list.columns" :data="list.tableData" @on-selection-change="selectionChange"></Table>
        </div>
        <div class="normal-list-page-ft clearfix">
          <Page class="fr" :total="queryData.totalRecord" :page-size="queryData.pageSize" :current="queryData.page" @on-change="changePage" @on-page-size-change="onPageSizeChange" show-total show-sizer></Page>
        </div>
      </div>

      <!--新建&修改-->
      <Modal v-model="modals.Entity.isShow" :loading="modals.Entity.loading" :mask-closable="false" :title="modals.Entity.title" @on-ok="postData">
        <Form ref="EntityFrom" :model="modals.Entity.formData" :rules="modals.Entity.rules" :label-width="120">
          <FormItem label="连接名称" prop="name">
            <Input placeholder="请填连接名称" v-model="modals.Entity.formData.name" style="width:300px;"/>
          </FormItem>
          <FormItem label="数据库驱动名称" prop="driverClass">
            <!-- <Input placeholder="请输入数据库驱动名称"  style="width:300px;" v-model="modals.Entity.formData.driverClass"/> -->
            <Select v-model="modals.Entity.formData.driverClass" @on-change="changeDriver" style="width:200px" >
              <Option v-for="item in driverList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
            <FormItem label="URL" prop="databaseUrl">
                <Input placeholder="" v-model="modals.Entity.formData.databaseUrl" style="width:300px;"/>
            </FormItem>
          <FormItem label="帐号" prop="databaseUser">
            <Input placeholder="" v-model="modals.Entity.formData.databaseUser" style="width:300px;"/>
          </FormItem>
          <FormItem label="密码" prop="databasePassword">
            <Input placeholder="" v-model="modals.Entity.formData.databasePassword" style="width:300px;"/>
          </FormItem>
        </Form>
      </Modal>

</div>
</div>
  </div>
</template>
<script>
import {
  ajaxGetEntity,
  ajaxPostEntity,
  ajaxPutEntity,
  ajaxDelEntity
} from "@/api/generine/data_source.js";
import moment from "moment";
import { Message } from "iview";

export default {
  name: "Entity",
  data() {
    return {
      // 弹出层数据
      modals: {
        Entity: {
          isShow: false,
          loading: true,
          type: "create", // create 新建，update 修改
          title: "新建",
          rules: {
            name: [
              {
                required: true,
                message: "请填连接名称",
                trigger: "blur"
              }
            ],
            driverClass: [
              {
                required: true,
                message: "数据库驱动",
                trigger: "blur"
              }
            ]
          },
          formData: {
            id: undefined,
            name: "",
            driverClass: "",
            databaseUrl: "",
            databaseUser: "",
            databasePassword: ""
          }
        }
      },
      driverList: [
        {
          label: "Mysql",
          value: "com.mysql.jdbc.Driver"
        },
        {
          label: "SQLServer2008+",
          value: "com.microsoft.sqlserver.jdbc.SQLServerDriver"
        },
        {
          label: "SQLServer2000",
          value: "net.sourceforge.jtds.jdbc.Driver"
        },
        {
          label: "Oracle",
          value: "oracle.jdbc.driver.OracleDriver"
        }
      ],
      jdbcDriver: "",
      databaseUrlList: [
          {
              label: "com.mysql.jdbc.Driver",
              value: "jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false"
          },
          {
              label: "com.microsoft.sqlserver.jdbc.SQLServerDriver",
              value: "jdbc:sqlserver://localhost:1433;database="
          },
          {
              label: "net.sourceforge.jtds.jdbc.Driver",
              value: "jdbc:jtds:sqlserver://localhost:1433;database="
          },
          {
              label: "oracle.jdbc.driver.OracleDriver",
              value: "jdbc:oracle:thin:@localhost:1521:databaseName"
          }
,      ],
      // 列表
      list: {
        loading: false,
        selections: [],
        // 列表展示数据
        tableData: [],
        // 表格表头
        columns: [
          {
            type: "selection",
            minWidth: 60,
            align: "center"
          },
          // 开始自动生成
          {
            title: "ID",
            minWidth: 60,
            key: "id"
          },
          {
            title: "名称",
            key: "name",
            minWidth:100
          },
          {
            title: "数据库驱动",
            key: "driverClass",
            minWidth:100
          },
          {
            title: "数据库连接",
            key: "databaseUrl",
            minWidth:100
          },
          {
            title: "帐号",
            key: "databaseUser",
            minWidth:100
          },
          {
            title: "密码",
            key: "databasePassword",
            minWidth:100
          },
          {
            title: "创建时间",
            key: "crtTime",
            minWidth:100,
            render: (h, params) => {
              let formatString = "YYYY-MM-DD HH:mm:ss";
              return moment
                .unix(params.row.crtTime / 1000)
                .format(formatString);
            }
          },
          {
            title: "更新时间",
            key: "updTime",
            minWidth:100,
            render: (h, params) => {
              let formatString = "YYYY-MM-DD HH:mm:ss";
              return moment
                .unix(params.row.updTime / 1000)
                .format(formatString);
            }
          },
          // 自动生成结束
          {
            title: "操作",
            align: "center",
            minWidth: 120,
            render: (h, params) => {
              return h("div", [
                // h(
                //   "Button",
                //   {
                //     props: {
                //       // icon: 'trash-b',
                //       type: "primary",
                //       size: "small"
                //     },
                //     style: {
                //       marginRight: "2px"
                //     },
                //     on: {
                //       click: () => {
                //         this.showUpdateModal(params.index);
                //       }
                //     }
                //   },
                //   "编辑"
                // ),
                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'left',
                      content: '编辑'
                    },
                    style: {
                      cursor: 'pointer'
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'primary',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px',
                          padding: '1px 2px'
                        },
                        on: {
                          click: () => {
                            this.showUpdateModal(params.index)
                          }
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: ' iconfont icon-bianjisekuai',
                            size: 18
                          }
                        })
                      ]
                    )
                  ]
                ),


                // h(
                //   "Button",
                //   {
                //     props: {
                //       // icon: 'edit',
                //       type: "error",
                //       size: "small"
                //     },
                //     on: {
                //       click: () => {
                //         this.delData([params.row.id]);
                //       }
                //     }
                //   },
                //   "删除"
                // )
                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'right',
                      content: '删除'
                    },
                    style: {
                      cursor: 'pointer'
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'error',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px',
                          padding: '1px 2px'
                        },
                        on: {
                          click: () => {
                            this.delData([params.row.id])
                          }
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: ' iconfont icon-shanchusekuai',
                            size: 18
                          }
                        })
                      ]
                    )
                  ]
                )
              ]);
            }
          }
        ]
      },
      // 页面查询数据
      queryData: {
        limit: 10,
        page: 1,
        totalRecord: 0,
        name: "",
        time: []
      }
    };
  },
  methods: {
    // 获取列表
    getTableData() {
      const that = this;
      that.queryData.totalRecord = undefined;
      that.queryData.startDate = that.queryData.time[0] || '';
      that.queryData.endDate = that.queryData.time[1] || '';
      // console.log(that.queryData)
      ajaxGetEntity(that.queryData).then(res => {
        that.list.tableData = res.data.list;
        that.queryData.totalRecord = res.data.totalRecord;
        that.queryData.page = res.data.pageNum;
      });
    },

    // 新建&修改
    postData() {
      const that = this;
      that.$refs["EntityFrom"].validate(valid => {
        if (valid) {
          // 新建
          if (!that.modals.Entity.formData.id) {
            ajaxPostEntity(that.modals.Entity.formData).then(res => {
              that.modals.Entity.isShow = false;
              that.modals.Entity.loading = false;
              if (!res.code) {
                that.getTableData();
                that.$Notice.success({
                  title: "保存成功!"
                });
              } else {
                that.$Notice.error({
                  title: res.message
                });
              }
            });
          } else {
            // 修改
            ajaxPutEntity(
              that.modals.Entity.formData.id,
              that.modals.Entity.formData
            ).then(res => {
              that.modals.Entity.isShow = false;
              that.modals.Entity.loading = false;
              if (!res.code) {
                that.getTableData();
                that.$Notice.success({
                  title: "保存成功!"
                });
              } else {
                that.$Notice.error({
                  title: res.message
                });
              }
            });
          }
        } else {
          that.modals.Entity.loading = false;
          that.$nextTick(() => {
            that.modals.Entity.loading = true;
          });
        }
      });
    },

    // 删除
    delData(ids) {
      if (!ids.length) {
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content:
          "<p>您确认删除id为 <strong>" +
          ids.toString() +
          "</strong> 的记录吗?</p><p>删除后将无法撤销，请谨慎操作！</p>",
        loading: true,
        onOk: () => {
          ajaxDelEntity({
            ids: ids
          }).then(res => {
            this.$Modal.remove();
            if (!res.data) {
              this.$Notice.success({
                title: "删除成功"
              });
              this.queryData.page = 1;
              this.getTableData();
            } else {
              this.$Notice.error({
                title: res.message
              });
            }
          });
        }
      });
    },

    // 排量删除
    batchDel() {
      let ids = [];
      this.list.selections.forEach(element => {
        ids.push(element.id);
      });
      if (!ids.length) {
        this.$Message.error({
          content: "请先选择要删除的项！",
          duration: 3
        });
      }
      this.delData(ids);
    },

    // 全选，不全选
    selectionChange(args) {
      this.list.selections = args;
    },
    //每页显示记录数变更
    onPageSizeChange(pageSize) {
      this.queryData.limit = pageSize;
      this.getTableData();
    },
    // 换页
    changePage(page) {
      this.queryData.page = page;
      this.getTableData();
    },
    clearTime () {
      this.queryData.time = [];
    },
    selectTime (event) {
      console.log(event)
      this.queryData.time = event;
    },
    //改变开始时间
    changeStartDate(date) {
      this.queryData.startDate = date;
    },
    //改变结束时间
    changeEndDate(date) {
      this.queryData.endDate = date;
    },
    // 查找
    goSearch() {
      this.getTableData();
    },
    //改变驱动地址
    changeDriver(value) {
        var databaseUrl = "";
        this.databaseUrlList.forEach(function (item, index) {
            if (item.label == value) {
                databaseUrl = item.value;
            }
        })
        this.modals.Entity.formData.databaseUrl = databaseUrl;
    },

    // 显示新建弹窗
    showCreateModal() {
      this.$refs["EntityFrom"].resetFields();
      this.modals.Entity.type = "create";
      this.modals.Entity.title = "新建";
      this.modals.Entity.formData = {};
      this.modals.Entity.isShow = true;
    },

    // 显示修改弹窗
    showUpdateModal(index) {
      this.$refs["EntityFrom"].resetFields();
      this.modals.Entity.type = "update";
      this.modals.Entity.title = "修改";
      this.modals.Entity.formData = JSON.parse(
        JSON.stringify(this.list.tableData)
      )[index];
      this.modals.Entity.isShow = true;
    }
  },
  created() {
    this.getTableData();
  }
};
</script>
